package com.service;

import com.dao.DepDAO;
import com.dao.EmpDAO;
import com.pojo.Dep;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

@Service
public class EmpService {

    @Autowired
    private EmpDAO empDAO;

    @Autowired
    private DepDAO depDAO;

    public Page  searchDep(Integer depId, String depName,int page, int size)
    {
        Specification<Dep>  specification = new Specification<Dep>() {
            List<Predicate> predicates = new ArrayList<>();
            @Override
            public Predicate toPredicate(Root<Dep> root, CriteriaQuery<?> cq, CriteriaBuilder cb) {

                if (depId!=null)
                {
                     Predicate  predicate1 =   cb.equal(root.get("depId"),depId);
                     predicates.add(predicate1);
                }
                if (depName!=null)
                {
                    Predicate predicate2 = cb.like(root.get("depName"),"%"+depName+"%");
                    predicates.add(predicate2);
                }
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };

        Sort sort = Sort.by(Sort.Order.asc("depId"));
        return depDAO.findAll(specification, PageRequest.of(page, size));

    }

    public List getAll() {

     /*
       Emp emp  = empDAO.findById(3).get();
       emp.setEmpName("aaa");
       empDAO.save(emp);
     */
        List list = empDAO.getAll();// empDAO.findAll();
        return list;


    }
}
